#!C:\Python24\python.exe
import cgitb;cgitb.enable()
import sajax1
import SyntaxParser

path = 'doc/interface/toc_list.txt'
toc_array = SyntaxParser.buildArray(path)
path = 'doc/interface/databases.txt'
standard_databases = SyntaxParser.buildArray(path)	
path = 'doc/interface/ref_entities.txt'
reference_entities = SyntaxParser.buildArray(path)
path = 'doc/interface/sta_entities.txt'
stat_entities = SyntaxParser.buildArray(path)
path = 'doc/interface/med_entities.txt'
medical_entities = SyntaxParser.buildHash(path)

default_time_value = 24
default_time_entity = 'hours'
default_location = 'GICU'
	
#returns an error in the database field
def validateDatabase(db):
	if db == "[DATABASE]":
		return "*Database required"
	
	input_databases = db.lower().split(" and ")
	
	for input_database in input_databases:
		input_database = input_database.strip()
		isValid = 0
		for standard_database in standard_databases:
			if input_database == standard_database:
				isValid = 1
				break
		if isValid == 0:
			return "*" + str(input_database) + " is not a valid database."
	
	return ''

#returns an error in the answer field
def validateanswer(ans):
	input_answer = []
		
	if ans == "[answer REQUIRED]":
		return "*answer required"

	if SyntaxParser.getTerm(ans.strip().lower(), medical_entities) == None:
		return "*Syntax error: Missing|Incorrect med_ent"
	
	return ''
	
def validateTimePeriod(time_period):

	time_identifiers = ["during the last"]
	time_entities = ["hours", "days", "weeks"]
	
	time_identifier_index = SyntaxParser.getIndex(time_period.strip(), time_identifiers, 0)
	if time_identifier_index != 0:
		return "*Syntax error: Missing time identifier"
		
	time_identifier = SyntaxParser.getKey(time_period.strip(), time_identifiers, time_identifier_index)

	time = time_period[time_identifier_index+len(time_identifier)+1:len(time_period)].strip()
	time_tokens = time.split()
	
	if len(time_tokens) != 2:
		return "*Syntax error: Time should be in the format of [tim_val][tim_ent]"
	
	if time_tokens[0].strip().isdigit() != 1:
		return "*Syntax error: tim_val should be an integer"
	
	has_time_entity = 0
	for time_entity in time_entities:
		if time_tokens[1].strip().lower() == time_entity.lower():
			has_time_entity = 1
			break
	if has_time_entity == 0:
		return "*Syntax error: tim_ent should be in ['hours', 'days', 'weeks']"
			
	return ''
	
def validateLocation(location):
	has_loc_entity = 0
	for database in standard_databases:
		if location.lower() == database.lower():
			has_loc_entity = 1
			break
	if has_loc_entity == 0:
		error_string = "*Syntax error: loc_ent should be in ["
		for database in standard_databases:
			error_string = error_string + "'" + database + "'"
		error_string += "]"
		return error_string

	return ''
	
def validateDemoCriterias(demo_criterias):
	if demo_criterias == "[DEMOGRAPHIC CRITERIAS]":
		return ''
	comparands = [">",">=","<","<=","=","<>"]
	
	input_criterias = []
	path = 'doc/interface/demo_entities.txt'
	demo_entities = SyntaxParser.buildArray(path)
	
	raw_input_demo_criterias = demo_criterias.lower().split(" and ")
	for raw_input_demo_criteria in raw_input_demo_criterias:
		criterias = raw_input_demo_criteria.split(" or ")
		for criteria in criterias:
			input_criterias.append(criteria)
		
	for input_criteria in input_criterias:
		has_dem_entity = 0
		
		if len(input_criteria) == 0:
			return "*Syntax error: Missing demo_entity"
			
		comparand = SyntaxParser.getComparand(input_criteria, SyntaxParser.getIndex(input_criteria, comparands, 0))
		demo_criteria_tokens = input_criteria.split(str(comparand))
		
		for demo_entity in demo_entities:
			if demo_criteria_tokens[0].strip().lower() == demo_entity.lower():
				has_dem_entity = 1
				break
		
		if has_dem_entity == 0:
			return "*Syntax error: Incorrect demo_entity"
		
		if len(demo_criteria_tokens) != 2:
			return "*Syntax error: Missing comparand"
			
		elif len(demo_criteria_tokens[1].strip()) == 0:
			return "*Syntax error: Missing value"
			
	return ''
	
def validateMedCriterias(medical_criterias):
	if medical_criterias == "[MEDICAL CRITERIAS]":
		return ''
		
	comparands = [">",">=","<","<=","=","<>"]
	
	input_criterias = []
	
	raw_input_medical_criterias = medical_criterias.lower().split(" and ")
	for raw_input_medical_criteria in raw_input_medical_criterias:
		criterias = raw_input_medical_criteria.split(" or ")
		for criteria in criterias:
			input_criterias.append(criteria)

	for input_criteria in input_criterias:
		has_med_entity = 0
		
		if len(input_criteria) == 0:
			return "*Syntax error: Missing med_entity"
			
		comparand = SyntaxParser.getComparand(input_criteria, SyntaxParser.getIndex(input_criteria, comparands, 0))
		med_criteria_tokens = input_criteria.split(str(comparand))
		
		# eg. [alsdkf > 20]
		if SyntaxParser.getTerm(med_criteria_tokens[0].strip().lower(), medical_entities) == None:
			return "*Syntax error: Incorrect medical_entity"
		
		# eg. [airway]
		if len(med_criteria_tokens) != 2:
			return "*Syntax error: Missing comparand"
			
		# eg. [airway = ]
		elif len(med_criteria_tokens[1].strip()) == 0:
			return "*Syntax error: Missing value"

	return ''
	
sajax1.sajax_init()
sajax1.sajax_export(validateDatabase)
sajax1.sajax_export(validateanswer)
sajax1.sajax_export(validateTimePeriod)
sajax1.sajax_export(validateLocation)
sajax1.sajax_export(validateDemoCriterias)
sajax1.sajax_export(validateMedCriterias)
sajax1.sajax_handle_client_request()
	
print """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>
	<head>
		<title>Hypothesis Testing</title>
		<style type="text/css">
			body {
				font-family: Verdana, Tahoma, Sans-serif;
				font-size: 10pt;
			 	margin-top: 0;
			 	margin-left: 0;
			}

			select, option, input {
				font-family: Verdana, Tahoma, Sans-serif;
				font-weight: normal;
				font-size: 8pt;
			}

			div.title {
			 	float:right;
				font-weight:bold;
				margin-top: 18px;
				clear: left;
				padding-right: 20px;
				color:#FFFFFF;
				background-color: #39638B
			}
			
			#banner {
			 	margin-top: 0;
			 	margin-left: 0;
			 	background-image: url('/images/top_banner_in02.gif');
			 	background-position: 227px;
				background-repeat: no-repeat;
				background-color:#39638B; 
			}
						
			#title {
			 	font-family: Arial, Tahoma, Sans-serif;
			 	margin-top: 10px;
			 	margin-left: 5px;
			 	margin-bottom: 10px;
			 	font-weight: bold;
			 	font-size: 12pt;
			}
			
			legend {
			 	font-weight: bold;
			 	font-size: 8pt;
			}
			
			fieldset {
			 	font-weight: bold;
			 	font-size: 8pt;
			}
			
			#hypothesis_test_form {
			 	width: 1100px;
				margin-left: 5px;
			}
			
			#db_error, #answer_error, #time_period1_error, #location1_error, #demo_criterias1_error, #med_criterias1_error, #time_period2_error, #location2_error, #demo_criterias2_error, #med_criterias2_error{
			 	font-size: 8pt;
			 	font-weight: normal;
			 	color: red;
			}
			
			#criteria_1, #criteria_2 {
			 	margin-top: 5px;
			}
			
			#link {
			 	float: right;
			 	margin-right: 5px;
			}
		</style>
		
		<script type='text/javascript'>
"""
sajax1.sajax_show_javascript()
print """
			function validate_database_cb(validateDatabase) {
			 		document.getElementById("db_error").innerHTML = validateDatabase;
			}
			
			function validate_answer_cb(validateanswer) {
			 		document.getElementById("answer_error").innerHTML = validateanswer;
			}
			
			function validate_time_period1_cb(validateTimePeriod1) {
			 		document.getElementById("time_period1_error").innerHTML = validateTimePeriod1;
			}
			
			function validate_time_period2_cb(validateTimePeriod2) {
			 		document.getElementById("time_period1_error").innerHTML = validateTimePeriod2;
			}
			
			function validate_location1_cb(validateLocation1) {
			 		document.getElementById("location1_error").innerHTML = validateLocation1;
			}
			
			function validate_location2_cb(validateLocation2) {
			 		document.getElementById("location2_error").innerHTML = validateLocation2;
			}
			
			function validate_demo_criterias1_cb(validateDemoCriterias1) {
			 		document.getElementById("demo_criterias1_error").innerHTML = validateDemoCriterias1;
			}
			
			function validate_demo_criterias2_cb(validateDemoCriterias2) {
			 		document.getElementById("demo_criterias2_error").innerHTML = validateDemoCriterias2;
			}
			
			function validate_medical_criterias1_cb(validateMedCriterias1) {
			 		document.getElementById("med_criterias1_error").innerHTML = validateMedCriterias1;
			}
			
			function validate_medical_criterias2_cb(validateMedCriterias2) {
			 		document.getElementById("med_criterias2_error").innerHTML = validateMedCriterias2;
			}
			
			function validate_database() {
			 	var db;
			 	db = document.getElementById("db").value;
			 	if (db == '')
                    db = "[DATABASE]";
			 	x_validateDatabase(db, validate_database_cb);
			}
			
			function validate_answer() {
			 	var answer;
			 	answer = document.getElementById("answer").value;
			 	if (answer == '')
                    answer = "[answer REQUIRED]";
			 	x_validateanswer(answer, validate_answer_cb);
			} 	
			
			function validate_time_period1() {
			 	var time_period1;
			 	time_period1 = document.getElementById("time_period1").value;
                if (time_period1 == '')                	
"""
print "time_period1 = \"DURING THE LAST " + str(default_time_value) + " " + default_time_entity.upper() + "\""
print """
			 	x_validateTimePeriod(time_period1, validate_time_period1_cb);
			}	
			
			function validate_time_period2() {
			 	var time_period2;
			 	time_period2 = document.getElementById("time_period2").value;
                if (time_period2 == '')                	
"""
print "time_period2 = \"DURING THE LAST " + str(default_time_value) + " " + default_time_entity.upper() + "\""
print """
			 	x_validateTimePeriod(time_period2, validate_time_period2_cb);
			}
			
			function validate_location1() {
			 	var location1;
			 	location1 = document.getElementById("location1").value;
			 	if (location1 == '')
"""
print "location1 = \"" + default_location.upper() + "\""
print """
			 	x_validateLocation(location1, validate_location1_cb);
			}
			
			function validate_location2() {
			 	var location2;
			 	location2 = document.getElementById("location2").value;
			 	if (location2 == '')
"""
print "location2 = \"" + default_location.upper() + "\""
print """
			 	x_validateLocation(location2, validate_location2_cb);
			}
			
			function validate_demo_criterias1() {
			 	var demo_criterias1;
				demo_criterias1 = document.getElementById("demo_criterias1").value; 
				if (demo_criterias1 == '')
                    demo_criterias1 = "[DEMOGRAPHIC CRITERIAS]";	
				x_validateDemoCriterias(demo_criterias1, validate_demo_criterias1_cb);
			}
			
			function validate_demo_criterias2() {
			 	var demo_criterias2;
				demo_criterias2 = document.getElementById("demo_criterias2").value; 
				if (demo_criterias2 == '')
                    demo_criterias2 = "[DEMOGRAPHIC CRITERIAS]";	
				x_validateDemoCriterias(demo_criterias2, validate_demo_criterias2_cb);
			}
			
			function validate_med_criterias1() {
			 	var med_criteras1;
			 	med_criterias1 = document.getElementById("med_criterias1").value;
			 	if (med_criterias1 == '')
                    med_criterias1 = "[MEDICAL CRITERIAS]";
			 	x_validateMedCriterias(med_criterias1, validate_medical_criterias1_cb);
			}
			
			function validate_med_criterias2() {
			 	var med_criteras2;
			 	med_criterias2 = document.getElementById("med_criterias2").value;
			 	if (med_criterias2 == '')
                    med_criterias2 = "[MEDICAL CRITERIAS]";
			 	x_validateMedCriterias(med_criterias2, validate_medical_criterias2_cb);
			}
		</script>
	</head>
	
	<body>
		<div id='banner'>
			<div class='title'>
				Clinical Data Mining Project Group
			</div>
		  	<div> 
				<a href='http://www.usyd.edu.au'>
					 <img src='/images/top_banner_in01.gif' width='227' height='52' alt='The University of Sydney' style='border: 0px;' class='decor' /> 
				</a>
			</div>
		</div>
		<div id='link'>
			<a href='cdal.py'>CDAL User Interface</a>
		</div>
		<div id='title'>
			Hypothesis Testing
		</div>
		
		<form name='hypothesis_testing_form' action="hypothesis.py" method="post">
			<div id='hypothesis_testing_form'>
				<div id='general'>
					<fieldset>
						<legend>General</legend>
						<div id='general_contents'>
							Perform<br/>
							<select name='test_category' id='test_category'>
								<option selected='selected' value='2 means t-test'>2 means t-test</option>
							</select><br/>
							TOC<br/>
							<select name='toc' id='toc'>
								<option selected='selected' value='SNOMED''>SNOMED</option>
							</select><br/>
							Database<br/>
							<input type='text' size='30' name='db' id='db' onkeyup='validate_database()' />
							<div id='db_error'></div>
							answer Required<br/>
							<input type='text' size='30' name='answer' id='answer' onkeyup='validate_answer()' />
							<div id='answer_error'></div>
							
							Confidence Interval<br/>
						 	<select name='ci' id='ci'>
								<option selected = 'selected' value='0.95'>0.95</option>
								<option value='0.975'>0.975</option>
								<option value='0.9'>0.9</option>
							</select><br/>
							
							Test Type<br/>
							<select name='test_type' id='test_type'>
								<option selected='selected' value='1'>Mean 1 = Mean 2</option>
								<option value='2'>Mean 1 > Mean 2</option>
								<option value='3'>Mean 1 < Mean 2</option>
							</select>
						</div>
						
					</fieldset>
				</div>
				
				<div id='criteria_1'>
					<fieldset>
						<legend>Criterias for Patient 1</legend>
						<table>
							<tr>
								<td>Demographic Criterias</td>
								<td><input type='text' size='100' name='demo_criterias1' id='demo_criterias1' onkeyup='validate_demo_criterias1();' />
								<td><div id='demo_criterias1_error'></div></td>
							</tr>
							<tr>
								<td>Medical Criterias</td>
								<td><input type='text' size='100' name='med_criterias1' id='med_criterias1' onkeyup='validate_med_criterias1();' />
								<td><div id='med_criterias1_error'></div></td>
							</tr>
							<tr>
								<td>Time Period</td>
								<td><input type='text' size='100' name='time_period1' id='time_period1' onkeyup='validate_time_period1();' />
								<td><div id='time_period1_error'></div></td>
							</tr>
							<tr>
								<td>Location</td>
								<td><input type='text' size='100' name='location1' id='location1' onkeyup='validate_location1();' />
								<td><div id='location1_error'></div></td>
							</tr>
						</table>
					</fieldset>
				</div>
					
				<div id='criteria_2'>
					<fieldset>
						<legend>Criterias for Patient 2</legend>
						<table>
							<tr>
								<td>Demographic Criterias</td>
								<td><input type='text' size='100' name='demo_criterias2' id='demo_criterias2' onkeyup='validate_demo_criterias2();' />
								<td><div id='demo_criterias2_error'></div></td>
							</tr>
							<tr>
								<td>Medical Criterias</td>
								<td><input type='text' size='100' name='med_criterias2' id='med_criterias2' onkeyup='validate_med_criterias2();' />
								<td><div id='med_criterias2_error'></div></td>
							</tr>
							<tr>
								<td>Time Period</td>
								<td><input type='text' size='100' name='time_period2' id='time_period2' onkeyup='validate_time_period2();' />
								<td><div id='time_period2_error'></div></td>
							</tr>
							<tr>
								<td>Location</td>
								<td><input type='text' size='100' name='location2' id='location2' onkeyup='validate_location2();' />
								<td><div id='location2_error'></div></td>
							</tr>
						</table>
					</fieldset>
				</div>
				
				<div id='test_button' style='text-align:right'><input type='submit' value='Test' /></div>
			</div>
		</form>
	</body>
</html>
""" % locals()
